package org.example;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.security.User;

import java.io.File;
import java.io.IOException;

public class HBasePoolUtils {
  private static final Log LOG = LogFactory.getLog(HBasePoolUtils.class);
  private static String userdir = "./config/";
  public static Configuration conf = null;
  private static String krb5File = null;
  private static String userName = null;
  private static String userKeytabFile = null;

  /*上一次登录时间*/
  public static Long lastRegTime = 0L;
  /*保持登录的时间*/
  public static int regInterval = 1000*60*60;

  private static Connection conn = null;

  static {
    try {
      init();
      login();
      conn = ConnectionFactory.createConnection(conf);
      lastRegTime = System.currentTimeMillis();
      LOG.info("Success to get connection.");
    } catch (IOException e) {
      LOG.error("Fail to get connection." + e);
      e.printStackTrace();
    }
  }

  public static void init() throws IOException {
    conf = HBaseConfiguration.create();
    conf.addResource(new Path(userdir + "core-site.xml"));
    conf.addResource(new Path(userdir + "hdfs-site.xml"));
    conf.addResource(new Path(userdir + "hbase-site.xml"));
  }

  public static void login() throws IOException {
    if (User.isHBaseSecurityEnabled(conf)) {
      LOG.info("login...");
      userName = "admin";
      userKeytabFile = userdir + "admin.keytab";
      krb5File = userdir + "krb5.conf";
      System.setProperty("java.security.krb5.conf", krb5File);
      System.setProperty("java.security.auth.login.config", userdir + "jaas.conf");
      LoginUtil.login(userName, userKeytabFile, krb5File, conf);
    }
  }

  public static Connection getConnection() {
    long nowTime = System.currentTimeMillis();
    if ((nowTime > (lastRegTime + regInterval))||(conn==null)||(conn.isClosed())) {
      LOG.info("lastRegTime:" + lastRegTime + " nowTime:" + nowTime);
      try {
        if (conn!=null) {
          conn.close();
        }
        init();
        login();
        conn = ConnectionFactory.createConnection(conf);
        lastRegTime = nowTime;
        LOG.info("Success to get connection.");
      } catch (IOException e) {
        LOG.error("Fail to get connection." + e);
        e.printStackTrace();
      }
    }
    return conn;
  }

  public static void close() {
    if (conn!=null) {
      try {
        conn.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
